package com.shuoyue.ycgk.ui.papergroups;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gyf.immersionbar.ImmersionBar;
import com.scwang.smartrefresh.layout.util.SmartUtil;
import com.shuoyue.ycgk.Constant;
import com.shuoyue.ycgk.R;
import com.shuoyue.ycgk.base.BaseMvpActivity;
import com.shuoyue.ycgk.base.ListWithPage;
import com.shuoyue.ycgk.entity.Paper;
import com.shuoyue.ycgk.entity.PaperSet;
import com.shuoyue.ycgk.entity.UserTestPaper;
import com.shuoyue.ycgk.entity.course_teacher.AppPrice;
import com.shuoyue.ycgk.ui.common.CollectContract;
import com.shuoyue.ycgk.ui.common.CstWebActivity;
import com.shuoyue.ycgk.ui.mine.vip.MyVipActivity;
import com.shuoyue.ycgk.ui.papergroups.adapter.PaperAdapter;
import com.shuoyue.ycgk.ui.pay.PrePaperSetOrderActivity;
import com.shuoyue.ycgk.ui.questionbank.practice.paperset.questionitem.DoPaperActivity;
import com.shuoyue.ycgk.utils.MyRichTextHelper;
import com.shuoyue.ycgk.utils.ShareUtil;
import com.shuoyue.ycgk.utils.SizeUtil;
import com.shuoyue.ycgk.views.dialog.common.HintConfirmDialog;
import com.shuoyue.ycgk.views.dialog.pricedialog.PriceDialog;
import com.zzhoujay.richtext.RichText;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public abstract class BasePaperGroupInfoActivity extends BaseMvpActivity<PaperContract.Presenter>
        implements PaperContract.View,
        CreatePagerSetContract.View,
        CollectContract.View {

    protected int type = 0;//自定义真题1，热点2，题库3，冲刺4,
    //1:真题;1冲刺,3自由,null题库
    @BindView(R.id.page_title)
    TextView pageTitle;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.price)
    TextView price;
    @BindView(R.id.price_org)
    TextView priceOrg;
    @BindView(R.id.introduct)
    TextView introduct;
    @BindView(R.id.recomend_recycleView)
    RecyclerView recomendRecycleView;
    @BindView(R.id.price2)
    TextView price2;
    @BindView(R.id.price_org2)
    TextView priceOrg2;
    @BindView(R.id.buy)
    Button buy;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.go_introduct_line)
    View goIntroductLine;
    @BindView(R.id.go_course_table_line)
    View goCourseTableLine;
    @BindView(R.id.go_introduct_line1)
    View goIntroductLine1;
    @BindView(R.id.go_course_table_line1)
    View goCourseTableLine1;
    @BindView(R.id.lay_tag_title_show)
    LinearLayout layTagTitleShow;
    @BindView(R.id.lay_tag_title)
    LinearLayout layTagTitle;
    @BindView(R.id.setNum)
    TextView setNum;
    @BindView(R.id.questionTotal)
    TextView questionTotal;
    @BindView(R.id.search_edit)
    EditText searchEdit;
    @BindView(R.id.lay_buy)
    LinearLayout layBuy;
    //    @BindView(R.id.vip_price)
//    TextView vipPrice;
    @BindView(R.id.free)
    TextView free;
    @BindView(R.id.lay_price)
    LinearLayout layPrice;
    @BindView(R.id.free2)
    TextView free2;
    @BindView(R.id.vip_price2)
    TextView vipPrice2;
    @BindView(R.id.vilidate)
    TextView vilidate;
    @BindView(R.id.lay_price2)
    LinearLayout layPrice2;
    @BindView(R.id.collection)
    ImageView collection;
    @BindView(R.id.lay_price_org)
    FrameLayout layPriceOrg;
    //    @BindView(R.id.lay_price_vip)
//    LinearLayout layPriceVip;
    @BindView(R.id.lay_price_org2)
    FrameLayout layPriceOrg2;
    @BindView(R.id.lay_price_vip2)
    LinearLayout layPriceVip2;
    CollectContract.Presenter collectPresenter;

    int id;
    private int mScrollY = 0;
    PaperAdapter paperAdapter;
    PaperSet paperSet;
    protected CreatePagerSetContract.Presenter createPresenter;

    protected boolean isLisScroll = true;

    ListWithPage listWithPage;
    TextView more;
   protected int subjectTypeId = -1;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_paper_set_info;
    }

    @Override
    protected void initView() {
        pageTitle.setText("详情");
        layTagTitleShow.setVisibility(isLisScroll ? View.VISIBLE : View.GONE);
        if (isLisScroll) {

            scrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
                private int lastScrollY = 0;
                private final int h = SmartUtil.dp2px(200);

                @Override
                public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    if (lastScrollY < h) {
                        scrollY = Math.min(h, scrollY);
                        mScrollY = scrollY > h ? h : scrollY;
                        layTagTitle.setAlpha(1f * mScrollY / h);

                        if (1f * mScrollY / h == 0) {
                            ImmersionBar.with(BasePaperGroupInfoActivity.this).statusBarDarkFont(false, 0.2f).init();
                        } else if (1f * mScrollY / h == 1) {
                            ImmersionBar.with(BasePaperGroupInfoActivity.this).statusBarDarkFont(true, 0.2f).init();
                        }
                    }
                    lastScrollY = scrollY;
                    //悬浮标题处理
                    int[] contentLocation = new int[2];
                    layTagTitleShow.getLocationInWindow(contentLocation); //获取在当前窗口内的绝对坐标，含toolBar
                    layTagTitleShow.getLocationOnScreen(contentLocation); //获取在整个屏幕内的绝对坐标，含statusBar
                    int layContentY = contentLocation[1];
                    if (layContentY <= 150) {
                        layTagTitle.setVisibility(View.VISIBLE);
                    } else {
                        layTagTitle.setVisibility(View.GONE);
                    }

                }
            });
        }
        recomendRecycleView.setLayoutManager(new LinearLayoutManager(mContext));
//        recomendRecycleView.addItemDecoration(new SpacesItemDecoration(SizeUtil.dip2px(mContext, 12), false));
        paperAdapter = new PaperAdapter(null);
        recomendRecycleView.setAdapter(paperAdapter);
        more = (TextView) LayoutInflater.from(mContext).inflate(R.layout.lay_more_paper, null);
//        paperAdapter.addFooterView(more);
        more.setOnClickListener(v -> {
            if (listWithPage != null) {
                String search = searchEdit.getText().toString();
                mPresenter.getPaperList(id, TextUtils.isEmpty(search) ? null : search, listWithPage.getCurrent() + 1);
            } else {
                String search = searchEdit.getText().toString();
                mPresenter.getPaperList(id, TextUtils.isEmpty(search) ? null : search, 1);
            }
//            paperAdapter.resetData(paperSet.getTopicTestDTOS());
        });
        paperAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (paperSet.getIsPay() == 1 || paperSet.getIsFree() == 1) {
                Paper paper = (Paper) adapter.getItem(position);
                createPaper(paper);
            } else {
                HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "提示", "请先购买题包");
                hintConfirmDialog.setOkListener(v -> {
                    if (paperSet != null && paperSet.getDefaultPrice() != null) {
                        PrePaperSetOrderActivity.start(mContext, paperSet,
                                paperSet.getDefaultPrice().getPrice(),
                                paperSet.getDefaultPrice().getId(), paperSet.getSubjectTypeId());
                    }
                    hintConfirmDialog.dismiss();
                });
                hintConfirmDialog.show();
            }
        });
        searchEdit.setOnEditorActionListener((v, actionId, event) -> {
            String search = searchEdit.getText().toString();
            mPresenter.getPaperList(id, TextUtils.isEmpty(search) ? null : search, 1);
            return false;
        });
    }

    @Override
    public void initData() {
        subjectTypeId = getIntent().getIntExtra("subjectTypeId", -1);

        id = getIntent().getIntExtra("id", -1);
        mPresenter = new PaperContract.Presenter();
        mPresenter.attachView(this);
        createPresenter = new CreatePagerSetContract.Presenter();
        createPresenter.attachView(this);
        collectPresenter = new CollectContract.Presenter();
        collectPresenter.attachView(this);
        mPresenter.getPaperInfo(id);

    }

    @Override
    protected void onResume() {
        super.onResume();
        String search = searchEdit.getText().toString();
        mPresenter.getPaperList(id, TextUtils.isEmpty(search) ? null : search, 1);
        mPresenter.getPaperInfo(id);
    }

    @OnClick({R.id.back})
    public void onViewClicked() {
        finish();
    }

    @OnClick({
            R.id.service,
            R.id.share,
            R.id.buy,
            R.id.lay_introduct,
            R.id.lay_comment,
            R.id.lay_introduct2,
            R.id.collection,
            R.id.delete,
            R.id.lay_comment2}
    )
    public void onViewClicked(View view) {
        if (paperSet == null) {
            return;
        }
        switch (view.getId()) {

            case R.id.service:
                if (Constant.isOpenServiceExploer) {
                    Uri uri = Uri.parse(Constant.serviceUrl);
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    startActivity(intent);
                } else {
                    CstWebActivity.start(mContext, Constant.serviceUrl, "咨询");

                }

                break;
            case R.id.share:
                if (paperSet != null)
                    ShareUtil.shareUrl(this, ShareUtil.PAPER_SET_URL + id,
                            paperSet.getTitle(),
                            paperSet.getBrief(),
                            null);
                break;
            case R.id.delete:
                searchEdit.setText("");
                mPresenter.getPaperList(id, null, 1);
                break;
            case R.id.buy:
                if (type == 1 && paperSet.getIsPay() == 0) {/////查询类型 1:历年真题  -1:题库 2:时政热点  3:自由组卷  4:我的题集
                    showBuyVIPTips();
                } else {
                    buy();
                }
                break;
            case R.id.lay_comment:
            case R.id.lay_comment2:
                goCourseTableLine.setVisibility(View.VISIBLE);
                goIntroductLine.setVisibility(View.INVISIBLE);
                goCourseTableLine1.setVisibility(View.VISIBLE);
                goIntroductLine1.setVisibility(View.INVISIBLE);
                float y1 = recomendRecycleView.getY();
                scrollView.scrollTo(0, (int) y1 - (SizeUtil.dip2px(mContext, 82)/**顶部title高度加边距**/) - layTagTitle.getHeight());
                break;
            case R.id.lay_introduct:
            case R.id.lay_introduct2:
                goCourseTableLine.setVisibility(View.INVISIBLE);
                goIntroductLine.setVisibility(View.VISIBLE);
                goCourseTableLine1.setVisibility(View.INVISIBLE);
                goIntroductLine1.setVisibility(View.VISIBLE);
                float y2 = introduct.getY();
                scrollView.scrollTo(0, (int) y2 /**- (SizeUtil.dip2px(mContext, 82)顶部title高度加边距)**/ - layTagTitle.getHeight());

                break;

            case R.id.collection:
                if (paperSet != null) {
                    if (paperSet.getIsCollect() == 1) {
                        collectPresenter.deleteCollection(paperSet.getId(), 3);
                    } else {
                        collectPresenter.saveCollect(paperSet.getId(), 3);
                    }
                    collection.setEnabled(false);
                }
                break;
        }
    }

    void showBuyVIPTips() {
        HintConfirmDialog hintConfirmDialog = new HintConfirmDialog(mContext, "提示",
                "<p>购买VIP可以直接解锁所有真题包，</p><p>也可以单独购买真题包</p>");
        hintConfirmDialog.setOkListener(v -> {
            MyVipActivity.start(mContext, true);
            hintConfirmDialog.dismiss();
        });
        hintConfirmDialog.setCancelListener(v -> {
            buy();
            hintConfirmDialog.dismiss();
        });
        hintConfirmDialog.setButtonText("购买习题包", "购买会员");
        hintConfirmDialog.show();
    }

    void buy() {
        if (paperSet != null) {
            if ((paperSet.getIsPay() == 1
                    || paperSet.getIsFree() == 1)
                    && (paperAdapter != null && paperAdapter.getData().size() > 0)) {
                Paper paper = paperAdapter.getItem(0);
                createPaper(paper);
            } else {

                if (paperSet.getProductPriceList() == null) {
                    PrePaperSetOrderActivity.start(mContext, paperSet,
                            paperSet.getDefaultPrice().getPrice(),
                            paperSet.getDefaultPrice().getId(), subjectTypeId);
                } else {
                    PriceDialog priceDialog = new PriceDialog(mContext, paperSet.getProductPriceList());
                    int finalSubjectTypeId = subjectTypeId;
                    priceDialog.addSelectCall(speed -> PrePaperSetOrderActivity.start(mContext, paperSet,
                            speed.getPrice(),
                            speed.getId(), finalSubjectTypeId));
                    priceDialog.show();
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        RichText.clear(this);
        super.onDestroy();
    }


    @Override
    public void setPaperSet(List<PaperSet> paperSets) {

    }

    @Override
    public void setPaperSet(ListWithPage<PaperSet> paperSets) {

    }

    @Override
    public void setPaperSetInfo(PaperSet paperInfo) {
        paperInfo.setIntroduce(paperInfo.getIntroduce());
        collection.setImageResource(paperInfo.getIsCollect() == 1 ? R.mipmap.collection_y : R.mipmap.collection_n);
        vilidate.setVisibility(paperInfo.getDefaultPrice() == null ? View.GONE : View.VISIBLE);
        vilidate.setText(paperInfo.getDefaultPrice() == null ? "" : ("有效期：" + paperInfo.getDefaultPrice().getEffectiveTime() + "天"));
        this.paperSet = paperInfo;
        setNum.setText(String.valueOf(paperInfo.getTotalPaper()));
        questionTotal.setText(String.valueOf(paperInfo.getTotalQuestion()));
        name.setText(paperInfo.getTitle());
        if (paperInfo.getIsPay() == 1) {
            buy.setText("开始练习");
        }
        if (paperInfo.getIsFree() == 1 || paperInfo.getDefaultPrice() == null) {
            free.setVisibility(View.VISIBLE);
            layPrice.setVisibility(View.GONE);
            free2.setVisibility(View.VISIBLE);
            layPrice2.setVisibility(View.GONE);
            layBuy.setVisibility(View.GONE);
        } else {
            AppPrice appPrice = paperInfo.getDefaultPrice();

            layPriceOrg.setVisibility(TextUtils.isEmpty(appPrice.getOriginalPrice())
                    ? View.GONE : View.VISIBLE);
            layPriceOrg2.setVisibility(TextUtils.isEmpty(appPrice.getOriginalPrice())
                    ? View.GONE : View.VISIBLE);
//            layPriceVip.setVisibility(null == appPrice.getVipPrice()
//                    || appPrice.getVipPrice() == appPrice.getPrice()
//                    ? View.GONE : View.VISIBLE);
            layPriceVip2.setVisibility(TextUtils.isEmpty(appPrice.getVipPrice())
                    ? View.GONE : View.VISIBLE);

            price.setText("￥" + appPrice.getPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
            price2.setText("￥" + appPrice.getPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
            priceOrg.setText("￥" + appPrice.getOriginalPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
            priceOrg2.setText("￥" + appPrice.getOriginalPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
//            vipPrice.setText("￥" + appPrice.getVipPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
            vipPrice2.setText("￥" + appPrice.getVipPrice());//((item.getPrice() % 1f == 0) ? ((int) item.getPrice()) : item.getPrice())
        }
        MyRichTextHelper.showRich(mContext, paperInfo.getIntroduce(), introduct);

    }

    @Override
    public void setPaperList(ListWithPage<Paper> listWithPage) {
        this.listWithPage = listWithPage;

        paperAdapter.removeAllFooterView();
        if (listWithPage.getTotal() == 0) {
            paperAdapter.addFooterView(more);
            more.setText("没有找到数据");
        } else if (listWithPage.getCurrent() < listWithPage.getPages()) {
            paperAdapter.addFooterView(more);
            more.setText("查看更多");
        }
        if (listWithPage.getCurrent() == 1) {
            paperAdapter.resetData(listWithPage.getRecords());
        } else {
            paperAdapter.addData(listWithPage.getRecords());
        }
    }

    @Override
    public void createPaperSuc(UserTestPaper userTestPaper) {
        DoPaperActivity.start(mContext, userTestPaper);

    }

    protected abstract void createPaper(Paper paper);

    @Override
    public void addCollectSuc() {
        collection.setImageResource(R.mipmap.collection_y);
        collection.setEnabled(true);
        paperSet.setIsCollect(1);

    }

    @Override
    public void deleteCollectSuc() {
        collection.setImageResource(R.mipmap.collection_n);
        collection.setEnabled(true);
        paperSet.setIsCollect(0);
    }


}
